package com.tierstall.client.presenter;

import java.util.ArrayList;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.view.client.ListDataProvider;
import com.tierstall.client.service.WebServices;
import com.tierstall.client.view.content.CV_addTier;
import com.tierstall.shared.GruppeDTO;
import com.tierstall.shared.Logger;
import com.tierstall.shared.Page;
import com.tierstall.shared.SearchQuery;
import com.tierstall.shared.TierDTO;
import com.tierstall.shared.UserDTO;

public class AddTierPresenterImpl extends
		AbstractContentViewPresenter<CV_addTier> implements
		CV_addTier.AddTierPresenter {

	private ArrayList<TierDTO> tierList;



	public AddTierPresenterImpl(WebServices rpcServices, String session_id,
			HandlerManager eventBus, MainPresenter mainPresenter,
			UserDTO currentUser) {
		super(rpcServices, session_id, eventBus, mainPresenter, currentUser);
		view = (CV_addTier) mainPresenter
				.getContentView(Page.ADD_TIER);
		this.view.setPresenter(this);
	}

	@Override
	public void go(HasWidgets container) {
		view.onInitialize();
		view.initForm();
		getGroups();
		mPresenter.setContentView(view);

	}
	
	private void getGroups() {
		rpcService.getRpcTierService().getGroups(sessionId,
				new AsyncCallback<ArrayList<GruppeDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						view.failed();

					}

					@Override
					public void onSuccess(ArrayList<GruppeDTO> result) {
						view.fillGroupCombo(result);

					}

				});

	}

	private void getFilteredResult(SearchQuery query) {
		rpcService.getRpcTierService().queryTiere(sessionId, query,
				new AsyncCallback<ArrayList<TierDTO>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Logger.CLIENT_ERROR("AddTierPresenter: Failure retrieving tier-list!");
						view.failed();
					}

					@Override
					public void onSuccess(ArrayList<TierDTO> result) {
						tierList = result;
						view.setData(result);

					}
				});
	}


	@Override
	public void onAddClicked(TierDTO tier) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void groupSelected(GruppeDTO group) {
		SearchQuery query = new SearchQuery();
		query.setGroup(group);
		getFilteredResult(query);		
	}
}
